package com.bupt.ilink.controller.innovationPlaza;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bupt.ilink.entity.User;
import com.bupt.ilink.entity.innovationPlaza.DTO.ProjectResponse;
import com.bupt.ilink.entity.innovationPlaza.DTO.ProjectdetailsIntroduceResponse;
import com.bupt.ilink.entity.innovationPlaza.DTO.ProjectdetailsMembersResponse;
import com.bupt.ilink.entity.innovationPlaza.DTO.ProjectdetailsMetaResponse;
import com.bupt.ilink.entity.innovationPlaza.InnovationTags;
import com.bupt.ilink.entity.innovationPlaza.ProjectUser;
import com.bupt.ilink.service.OssService;
import com.bupt.ilink.service.innovationPlaza.ProjectService;
import com.bupt.ilink.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.bind.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/innovationPlaza/project")
public class ProjectController {
    @Autowired
    private ProjectService projectService;
    //    大创广场概览页获取全部大创概览，需要基于 排序
//    @GetMapping("/getAllMeta")
//    public List<ProjectResponse> getAllProjectMeta(@RequestParam(required = false, defaultValue = "createdTime") String sortBy) {
//        return projectService.getAllProjectMeta(sortBy);
//    }

    /**
     * @author dzy
     * @return 最常使用的8个标签(List<InnovationTags>形式)
     */
    @GetMapping("/getCommonProjectTags")
    public R getCommonDatasetTags(){
        try {
            return R.ok(projectService.getCommonTags());
        } catch(Exception e){
            return R.failure("内部服务器错误：" + e);
        }
    }

    //获取大创概览的api!
    @GetMapping("/getALLProjects")
    public IPage<ProjectResponse> getALLProjectsBy(
            @RequestParam(required = false, defaultValue = "") String sentence,
            @RequestParam(required = false, defaultValue = "") List<String> tags,
            @RequestParam(required = false, defaultValue = "createdTime") String sortBy,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(required = false, defaultValue = "10") int pageSize,
            @RequestParam(required = false) Integer projectStyle, // 添加 projectStyle 参数
            @AuthenticationPrincipal UserDetails userDetails) {

        User user = (User) userDetails;
        return projectService.getALLProjects(sentence, tags, sortBy, pageNum, pageSize, user.getUserId(), projectStyle);
    }


//    @GetMapping("/getAllMetaPage")
//    public IPage<ProjectResponse> getAllProjectMetaPage(@RequestParam(required = false, defaultValue = "createdTime") String sortBy,
//                                                        @RequestParam int pageNum) {
//        int pageSize=10;
//        return projectService.getAllProjectMetaPage(sortBy, pageNum, pageSize);
//    }

//    查看页面
//    @GetMapping("/getProject")
//    public List<ProjectResponse> getProjectByID(@RequestBody BigInteger projectId){
//        return projectService.getAllProjectDetails();
//    }
//
//    //基于标签获取大创概览
//    @GetMapping("/searchProjectsByTags")
//    public IPage<ProjectResponse> searchProjectsByTags(
//            @RequestParam List<String> tags,
//            @RequestParam(required = false, defaultValue = "createdTime") String sortBy,
//            @RequestParam(defaultValue = "1") int pageNum,
//            @RequestParam(required = false,defaultValue = "10") int pageSize) {
//        return projectService.searchProjectsByTags(tags, sortBy, pageNum, pageSize);
//    }
//
//    //基于关键词对标题的模糊查询
//    @GetMapping("/searchProjectByname")
//    public List<ProjectResponse> searchProjectsByName(@RequestParam String sentence, @RequestParam(required = false) String sortBy) {
//        return projectService.searchProjectsByName(sentence,sortBy);
//    }
//    @GetMapping("/searchProjectByNamePage")
//    public IPage<ProjectResponse> searchProjectsByNamePage(
//            @RequestParam String sentence,
//            @RequestParam(required = false, defaultValue = "createdTime") String sortBy,
//            @RequestParam(defaultValue = "1") int pageNum
//           ) {
//        int pageSize=10;
//        return projectService.searchProjectsByNamePage(sentence, sortBy, pageNum, pageSize);
//    }

    //获取项目的详细信息上面
    @GetMapping("/getProjectDetailsMeta")
    public ProjectdetailsMetaResponse getProjectDetailsMeta(@RequestParam Long projectId) {
        return projectService.getProjectDetailsMeta(projectId);
    }
    //获取项目的详细信息：项目介绍
    @GetMapping("/getProjectDetailsIntroduce")
    public ProjectdetailsIntroduceResponse getProjectDetails(@RequestParam Long projectId) {
        return projectService.getProjectIntroduce(projectId);
    }

    //获取项目的详细信息：项目成员
    @GetMapping("/getProjectDetailsmembers")
    public List<ProjectUser> getProjectMembers(@RequestParam Long projectId) {//,@RequestParam BigInteger userId
        return projectService.getProjectMembers(projectId);
    }

    //项目点赞:加一个状态
    @PostMapping("/toggleLike")
    public R toggleLike(@RequestParam Long projectId,  @AuthenticationPrincipal UserDetails userDetails) {
        try {
            User user = (User) userDetails;
            String result= projectService.toggleLike(projectId, user.getUserId());
            return R.ok(result);
        }catch (Exception e){
            return R.failure(e.getMessage());
        }

    }
    //项目分享
    @PostMapping("/shareProject")
    public R shareProject(@RequestParam Long projectId) {
        boolean isSuccess = projectService.incrementShareNum(projectId);
        if(isSuccess){
            return R.ok("分享量+1");
        } else {
            return R.failure("项目分享失败");
        }
    }

    //项目浏览
    @PostMapping("/clickProject")
    public R clickProject(@RequestParam Long projectId) {
        boolean isSuccess = projectService.incrementClickNum(projectId);
        if(isSuccess){
            return R.ok("点击量+1");
        } else {
            return R.failure("项目浏览失败");
        }
    }

    //写入项目信息，创建项目
    @PostMapping("/InsertProjectdata")
    public R InsertProjectdata(@RequestBody ProjectResponse ProjectData) {
        boolean isSuccess = projectService.saveProject(ProjectData);
        if(isSuccess){
            return R.ok("项目创建成功");
        }else{
            return R.failure("项目创建失败");
        }
    }


    @Autowired
    private OssService ossService; // 假设你有一个OSS服务类用于文件上传

    @PostMapping("/uploadProjectImage")
    public R uploadProjectImage(
            @RequestParam("file") MultipartFile file,
            @RequestParam("projectId") BigInteger projectId
    ) {
        // 获取原始文件名
        String originalFilename = file.getOriginalFilename();

        // 获取文件扩展名
        String fileExtension = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        } else {
            return R.failure("文件解析扩展名出现错误：" + originalFilename);
        }

        // 生成新的文件名
        String newFilename = projectId + "_" + System.currentTimeMillis() + fileExtension;

        // 定义文件上传路径
        String filePath = "study-square/" + projectId + "/";

        // OSS 上传文件
        boolean uploadSuccess = ossService.uploadFile(file, filePath, newFilename);
        if (uploadSuccess) {
            // 获取文件的完整URL
            String fileUrl = ossService.getFileUrl(filePath + newFilename);
            if (fileUrl != null) {
                return R.ok("图片上传成功，文件URL: " + fileUrl);
            } else {
                return R.failure("获取文件URL失败: " + newFilename);
            }
        } else {
            return R.failure("图片上传失败: " + file.getOriginalFilename());
        }
    }







}


























